import 'package:fish_redux/fish_redux.dart';
import 'package:signature/generated/i18n.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'dart:io';

Effect<InstallViewState> buildEffect() {
  return combineEffects(<Object, Effect<InstallViewState>>{
    InstallViewAction.onTapPic: _onTapPic,
    InstallViewAction.onTapAddPic: _onTapAddPic,
    InstallViewAction.onSubmit: _onSubmit,
    InstallViewAction.onPayTypeTap: _onPayTypeTap,
    InstallViewAction.onCommunityTap: _onCommunityTap,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<InstallViewState> ctx) async {
  ResultData res = await CommonNetWork.orderPayType();
  if (res.success) {
    List data = res.data;
    List<OrderPayTypeModel> payList = data
        .map<OrderPayTypeModel>((e) => OrderPayTypeModel(
              typeName: CommonUtils.checkNullToString(e['TypeName']),
              typeID: CommonUtils.checkNullToString(e['TypeId']),
            ))
        .toList();
    ctx.state.payList = payList;
  }
  if (ctx.state.isDetail) {
    ResultData res = await CommonNetWork.installDetailView(ctx.state.itemID);
    if (res.success) {
      InstallDetailModel model =
          InstallDetailModel.fromJson(res.data, ctx.state.payList);
      String photo = CommonUtils.checkNullToString(res.data['OtherpayPhoto']);
      if (photo.length != 0) ctx.state.orderPhoto = photo.split(',');
      ctx.state.model = model;
    } else {
      await CommonUtils.showAlertView(ctx.context, res.desc);
      Navigator.pop(ctx.context);
      return;
    }
  } else {
    ResultData sysRes = await CommonNetWork.getSystemInstallInfo();
    if (sysRes.success) {
      List data = sysRes.data;
      if (data.isNotEmpty) {
        bool open = false;
        List values = data[0]['ConfigValue'];
        for (var map in values) {
          if (map['Value'] == '开户立装收费') {
            open = map['Key'] == '1';
          }
        }
        if (!open) {
          await CommonUtils.showAlertView(ctx.context, '未开通开户立装收费功能');
          Navigator.pop(ctx.context);
          return;
        }
      }
    }
  }
  ctx.dispatch(InstallViewActionCreator.onAction());
}

void _onTapAddPic(Action action, Context<InstallViewState> ctx) async {
  CommonUtils.closeKey(ctx.context);
  File imgFile = await CommonUtils.showImagePicker(ctx.context);
  if (imgFile != null) {
    ctx.dispatch(InstallViewActionCreator.setOrderPhoto(imgFile));
  }
}

void _onTapPic(Action action, Context<InstallViewState> ctx) async {
  CommonUtils.closeKey(ctx.context);
  pushPhoto(file) async {
    List<GalleryExampleItem> items = ctx.state.orderPhoto.map((e) {
      int index = ctx.state.orderPhoto.indexOf(e);
      return GalleryExampleItem(
        id: '$index',
        resource: e,
      );
    }).toList();
    items = await CommonUtils.showPhotoAlbumView(
      ctx.context,
      initialIndex: ctx.state.orderPhoto.indexOf(file),
      galleryItems: items,
    );
  }

  var file = action.payload;
  if (ctx.state.isDetail) {
    pushPhoto(file);
  } else {
    int res =
        await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.orderPhoto.remove(file);
      ctx.dispatch(InstallViewActionCreator.onAction());
    } else if (res == 0) {
      pushPhoto(file);
    }
  }
}

void _onSubmit(Action action, Context<InstallViewState> ctx) async {
  CommonUtils.closeKey(ctx.context);
  String error = '';
  if (ctx.state.moneyTextController.text.length == 0) error = '请输入报装金额';
  if (ctx.state.payTay == null) error = '请选择支付方式';
  if (ctx.state.idCardTextController.text.length == 0) error = '请输入身份证号';
  if (ctx.state.addressTextController.text.length == 0) error = '请输入报装地址';
  if (ctx.state.communityInfo == null) error = '请选择报装小区';
  if (ctx.state.phoneTextController.text.length == 0) error = '请输入联系方式';
  if (ctx.state.nameTextController.text.length == 0) error = '请输入姓名';
  if (error.length != 0) {
    CommonUtils.showErrorInfo(ctx.context, error);
    return;
  }
  var index = await CommonUtils.showOKCanceltView(
      ctx.context, '是否确定报装信息正确：报装金额:${ctx.state.moneyTextController.text}');
  if (index != 1) return;

  CommonUtils.showWaitLoading(ctx.context, descText: '提交数据中');
  String photo = '';
  if (ctx.state.orderPhoto.length != 0) {
    List<String> images =
        await CommonNetWork.multiUploadImgs(ctx.state.orderPhoto);
    photo = images.join(',');
  }

  ResultData res = await CommonNetWork.addInstallUser(
    userName: ctx.state.nameTextController.text,
    phone: ctx.state.phoneTextController.text,
    address: ctx.state.addressTextController.text,
    communityName: ctx.state.communityInfo.name,
    communityID: ctx.state.communityInfo.itemID,
    payType: ctx.state.payTay.typeID,
    money: ctx.state.moneyTextController.text,
    idCard: ctx.state.idCardTextController.text,
    photo: photo,
  );
  Navigator.pop(ctx.context);
  if (res.success) {
    await CommonUtils.showAlertView(ctx.context, '报装信息提交成功');
    bus.emit('refreshList');
    Navigator.pop(ctx.context);
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}

void _onPayTypeTap(Action action, Context<InstallViewState> ctx) async {
  CommonUtils.closeKey(ctx.context);
  int index = ctx.state.payTay == null
      ? 0
      : ctx.state.payList.indexOf(ctx.state.payTay);
  List<String> titles =
      ctx.state.payList.map<String>((e) => e.typeName).toList();
  int res = await CommonUtils.showCupertinoPicker(ctx.context, titles,
      initialIndex: index);
  if (res != null) {
    ctx.state.payTay = ctx.state.payList[res];
    ctx.dispatch(InstallViewActionCreator.onAction());
  }
}

void _onCommunityTap(Action action, Context<InstallViewState> ctx) async {
  CommonUtils.closeKey(ctx.context);
  var res =
      await CommonUtils.pushRoute(ctx.context, RoutePath.selectCommunityView);
  if (res != null) {
    ctx.state.communityInfo = res;
    ctx.dispatch(InstallViewActionCreator.onAction());
  }
}
